package cn.bluech.lib.ui.widget.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;

import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.StringRes;

import java.lang.reflect.Field;

/**
 * Description:
 * Create by Codeant on 2019/9/6.
 */
public class BaseDialog {
    protected Context ctx;
    protected AlertDialog.Builder builder;
    protected AlertDialog dialog;
    protected View rootView;

    private boolean isLock;
    // 如果使用isLock,dialog的显示状态失效,这里做状态保存
    private boolean isShowing;


    public BaseDialog(Context ctx, View view){
        this.ctx = ctx;
        this.rootView = view;

        builder = new AlertDialog.Builder(ctx);
        if(null!=rootView) {
            builder.setView(rootView);
        }
    }

    public BaseDialog(Context context, @LayoutRes int lyId){
        this(context,View.inflate(context,lyId,null));
    }

    public BaseDialog(Context context){
        this(context,null);
    }

    public final <T extends View> T findViewById(@IdRes int id) {
        if(null==rootView)
            return null;
        return rootView.findViewById(id);
    }

    protected void lockDialog(boolean lock){
        try{
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog,!lock);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    // 这里会一起限制掉点击关闭弹窗，必须手动调用dismiss()
    public BaseDialog setCancelable(boolean cancelable) {
        builder.setCancelable(cancelable);
        isLock = !cancelable;
        return this;
    }

    public BaseDialog setIcon(@DrawableRes int iconId) {
        builder.setIcon(iconId);
        return this;
    }

    public BaseDialog setIcon(Drawable icon) {
        builder.setIcon(icon);
        return this;
    }

    public BaseDialog setTitle(CharSequence title) {
        builder.setTitle(title);
        return this;
    }

    public BaseDialog setTitle(@StringRes int titleId) {
        return setTitle(ctx.getText(titleId));
    }

    public BaseDialog setView(View view) {
        if(null!=view){
            rootView = view;
            builder.setView(view);
        }

        return this;
    }

    public BaseDialog setView(@LayoutRes int lyId) {
        return setView(View.inflate(ctx,lyId,null));
    }

    public BaseDialog setMessage(CharSequence message) {
        builder.setMessage(message);
        return this;
    }

    public BaseDialog setMessage(@StringRes int messageId) {
        return setMessage(ctx.getText(messageId));
    }

    public BaseDialog setPositiveButton(CharSequence text, final OnClickListener listener) {
        builder.setPositiveButton(text, (dialog, which) -> {
            if(null!=listener)
                listener.onClick(BaseDialog.this,which);
        });

        return this;
    }

    public BaseDialog setPositiveButton(@StringRes int textId, final OnClickListener listener) {
        return setPositiveButton(ctx.getText(textId),listener);
    }

    public BaseDialog setNegativeButton(CharSequence text, final OnClickListener listener) {
        builder.setNegativeButton(text, (dialog, which) -> {
            if(null!=listener)
                listener.onClick(BaseDialog.this,which);
        });

        return this;
    }

    public BaseDialog setNegativeButton(@StringRes int textId, final OnClickListener listener) {
        return setNegativeButton(ctx.getText(textId),listener);
    }

    public BaseDialog setNeutralButton(CharSequence text, final OnClickListener listener) {
        builder.setNeutralButton(text, (dialog, which) -> {
            if(null!=listener)
                listener.onClick(BaseDialog.this,which);
        });

        return this;
    }

    public BaseDialog setNeutralButton(@StringRes int textId, final OnClickListener listener) {
        return setNeutralButton(ctx.getText(textId),listener);
    }

    public boolean isShowing(){
        return isShowing; //(null!=dialog)&&(dialog.isShowing());
    }

    public BaseDialog show(){
        if(null==dialog) {
            dialog = builder.create();
            dialog.setOnShowListener(dialog -> isShowing = true);
            dialog.setOnDismissListener(dialog -> isShowing = false);
            // dialog.setOnCancelListener(); // 手动调用dismiss()时回调

        }
        if(!isShowing()){
            dialog.show();
//            dialog.getWindow().setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);

//            View view = dialog.getWindow().getDecorView();//.setBackgroundColor(Color.parseColor("#00ffffff"));
//            ViewGroup.LayoutParams p = view.getLayoutParams();
//            p.width = -2; // 这个是无效的
//            view.setLayoutParams(p);
//
//            ViewGroup.LayoutParams pp = ((FrameLayout) view).getChildAt(0).getLayoutParams();
//            pp.width = -2; // 这个是msg的大小，有效，但外层装饰物大小不变
//            ((FrameLayout) view).getChildAt(0).setLayoutParams(pp);
//
//            WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
//            params.width = /*100;*/WindowManager.LayoutParams.WRAP_CONTENT; // 这里指定大小是有效的，但指定包含内容是无效的
//            params.height=WindowManager.LayoutParams.WRAP_CONTENT;
//            dialog.getWindow().setAttributes(params);

            if(isLock){
                lockDialog(true);
            }
        }

        return this;
    }

    public BaseDialog show(CharSequence title,CharSequence msg){
        setTitle(title);
        setMessage(msg);
        return show();
    }

    public BaseDialog show(@StringRes int titleId,@StringRes int msgId){
        return show(ctx.getText(titleId),ctx.getText(msgId));
    }

    public BaseDialog show(CharSequence msg){
        setMessage(msg);
        return show();
    }

    public BaseDialog show(@StringRes int msgId){
        return show(ctx.getText(msgId));
    }

    public void dismiss(){
        // isShowing()只有在真正显示出来才为true
        if(null!=dialog) {// &&isShowing() 会导致当弹窗还没弹出时就调用dismiss导致弹窗不消失
            if(isLock){
                lockDialog(false);
            }
            dialog.dismiss();
        }
    }


    public interface OnClickListener {
        void onClick(BaseDialog dialog, int which);
    }
}
